import { useState, useEffect } from 'react';
import { Form, Input, Select, Switch, Upload,App,Modal, TreeSelect } from 'antd';
import store from '@/store';
const { Option } = Select;
import ImgCrop from 'antd-img-crop';
import imageCompression from 'browser-image-compression';

const UserForm = ({ form, onFinish, roles = [], departmentId, isEditing = false,departments }) => {
  const { message } = App.useApp();
  const state = store.getState();
  const token = state.user.token;
  // 监听表单avatar字段变化，更新文件列表
  const avatarValue = Form.useWatch('avatar', form);
  const [fileList, setFileList] = useState([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');

  const handleChange = ({ fileList: newFileList, file }) => {
    if(file.status==undefined){
      newFileList = []
    }
    if (file.status == 'done') {
      const result = file.response;
      if (result.code == 200) {
        form.setFieldsValue({ avatar: result.data });
      } else {
        newFileList = []
        form.setFieldsValue({ avatar: '' });
        message.error(result.msg || '上传失败');
      }
    }
    setFileList(newFileList);
  };
  // 上传头像相关函数
  const handlePreview = async (file) => {
    let src = file.url;
    if (!src) {
      src = await new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    setPreviewImage(src);
    setPreviewOpen(true);
  };

  const handleRemove = (file) => {
    const index = fileList.indexOf(file);
    const newFileList = fileList.slice();
    newFileList.splice(index, 1);
    setFileList(newFileList);
    form.setFieldsValue({ avatar: '' });
  };
  const beforeUpload = async (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 格式的文件!');
      return false;
    }
    
    // 压缩图片
    const options = {
      maxSizeMB: 0.5, // 最大 500KB
      maxWidthOrHeight: 200, // 最大宽度或高度为 200px
      useWebWorker: false,
    };

    try {
      // 压缩图片
      const compressedFile = await imageCompression(file, options);
      
      // 检查压缩后的文件大小
      const isLt500kb = compressedFile.size / 1024 < 500;
      if (!isLt500kb) {
        message.error('头像大小压缩后仍然超过 500kb!');
        return false;
      }

      // 返回压缩后的文件
      return compressedFile;
    } catch (error) {
      console.error('图片压缩失败:', error);
      message.error('图片压缩失败!');
      return false;
    }
  };

  useEffect(() => {
    if (avatarValue) {
      // 确保avatarValue是字符串再创建文件列表项
      if (typeof avatarValue === 'string') {
        // 如果avatar有值，创建一个文件列表项
        setFileList([{
          uid: '-1',
          name: 'avatar.png',
          status: 'done',
          url: avatarValue,
          thumbUrl: avatarValue
        }]);
      } else {
        // 如果avatarValue不是字符串，清空文件列表
        setFileList([]);
      }
    } else {
      // 如果avatar没有值，清空文件列表
      setFileList([]);
    }
  }, [avatarValue]);
  return (
    <>
      <Form
        name="user-form"
        form={form}
        layout="vertical"
        onFinish={onFinish}
        initialValues={{
          gender: true,
          departmentId: departmentId
        }}
      >
        <Form.Item name="userId" hidden>
          <Input />
        </Form.Item>
        
        {!isEditing && (
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
        )}

        <Form.Item
          name="nickname"
          label="昵称"
          rules={[{ required: true, message: '请输入昵称!' }]}
        >
          <Input placeholder="请输入昵称" />
        </Form.Item>

        {!isEditing && (
          <>
            <Form.Item
              name="password"
              label="密码"
              rules={[
                { required: true, message: '请输入密码!' },
                { min: 6, message: '密码长度不能少于6位' }
              ]}
              hasFeedback
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>

            <Form.Item
              name="confirmPassword"
              label="确认密码"
              dependencies={['password']}
              hasFeedback
              rules={[
                { required: true, message: '请确认密码!' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致!'));
                  },
                }),
              ]}
            >
              <Input.Password placeholder="请再次输入密码" />
            </Form.Item>
          </>
        )}

        <Form.Item 
          name="avatar" 
          label="头像"
          rules={[{ required: true, message: '请上传头像!' }]}
          >
          <ImgCrop rotationSlider>
            <Upload
              headers={{
                Authorization: token,
              }}
              action="/file/upload"
              listType="picture-card"
              fileList={fileList}
              beforeUpload={beforeUpload}
              onChange={handleChange}
              onPreview={handlePreview}
              onRemove={handleRemove}
            >
              {fileList.length < 1 && '+ 上传'}
            </Upload>
          </ImgCrop>
        </Form.Item>

        <Form.Item 
          name="gender" 
          label="性别"
          rules={[{ required: true, message: '请选择性别!' }]}
          >
          <Switch 
            checkedChildren="男" 
            unCheckedChildren="女" 
          />
        </Form.Item>

        <Form.Item
          name="phone"
          label="手机号"
          rules={[{ required: true, message: '请输入手机号!' }]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>

        <Form.Item 
          name="departmentId" 
          label="部门"
          rules={[{ required: true, message: '请选择部门!' }]}
        >
          <TreeSelect
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={departments}
            placeholder="请选择部门"
            fieldNames={{ label: 'departmentName', value: 'id', children: 'children' }}
            treeDefaultExpandAll
          />
        </Form.Item>

        <Form.Item name="roleId" label="角色" rules={[{ required: true, message: '请选择角色!' }]}>
          <Select placeholder="请选择角色">
            {roles.map(role => (
              <Option key={role.value} value={role.value}>{role.label}</Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item name="remark" label="备注">
          <Input.TextArea placeholder="请输入备注" rows={3} />
        </Form.Item>
      </Form>
      <Modal
        open={previewOpen}
        title="图片预览"
        footer={null}
        onCancel={() => setPreviewOpen(false)}
      >
        <img
          style={{ width: '100%' }}
          src={previewImage}
        />
      </Modal>
    </>
  );
};

export default UserForm;